package com.wangyadong.hobby.concurrent;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

public class CyclicBarrierDemo {
    private static final int num = 10;

    private static final CyclicBarrier cyclicBarrier = new CyclicBarrier(num + 1, () -> {
        CountDownLatchDemo.PRINT_CONSUMER.accept("执行屏障");
    });

    public static void main(String[] args) throws InterruptedException, BrokenBarrierException {
        for (int i = 0; i < num; i++) {
            final int index = i;
            Thread thread = new Thread(() -> {
                try {
                    CountDownLatchDemo.PRINT_CONSUMER.accept("--------------子任务开始执行----------------");
                    TimeUnit.SECONDS.sleep(2);
                    CountDownLatchDemo.PRINT_CONSUMER.accept("--------------子任务开始执行完毕-------------");
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    CountDownLatchDemo.PRINT_CONSUMER.accept("--------------发生异常----------------" + cyclicBarrier.isBroken());
                    try {
                        cyclicBarrier.await();
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    } catch (BrokenBarrierException ex) {
                        ex.printStackTrace();
                    }
                }
                try {
                    TimeUnit.SECONDS.sleep(2);
                    cyclicBarrier.await();
                    CountDownLatchDemo.PRINT_CONSUMER.accept("--------------子任务再次执行完毕-------------");
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });

            thread.start();
            TimeUnit.SECONDS.sleep(3);
            Thread.currentThread().interrupt();
        }
        cyclicBarrier.await();
        System.out.println("结束");
        cyclicBarrier.await();
        CountDownLatchDemo.PRINT_CONSUMER.accept("--------------------------");
    }
}
